package controller

import (
	"blog/model"
	"blog/utils/errmsg"
	// "fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func AddArticle(ctx *gin.Context) {
	var data model.Article
	_ = ctx.ShouldBindJSON(&data)

	code := model.CreateArticle(&data)
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

func GetCateArticle(ctx *gin.Context) {
	// pageSize, _ := strconv.Atoi(ctx.Query("pagesize"))
	// currentPage, _ := strconv.Atoi(ctx.Query("currentPage"))
	// fmt.Println("-------------------", pageSize, currentPage)
	id, _ := strconv.Atoi(ctx.Param("id"))
	// name := ctx.Param("name")
	data, code := model.GetCateArt(id)

	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

func GetArtInfo(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	data, code := model.GetArticleInfo(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

func GetArtList(ctx *gin.Context) {
	title := ctx.Query("title")
	if len(title) == 0 {
		data, code := model.GetArticleList()
		ctx.JSON(http.StatusOK, gin.H{
			"status":  code,
			"data":    data,
			"message": errmsg.GetErrMsg(code),
		})
	} else {
		data, code := model.SearchArticle(title)
		ctx.JSON(http.StatusOK, gin.H{
			"status":  code,
			"data":    data,
			"message": errmsg.GetErrMsg(code),
		})
	}
}

func EditArticle(ctx *gin.Context) {
	var data model.Article
	id, _ := strconv.Atoi(ctx.Param("id"))
	_ = ctx.ShouldBindJSON(&data)

	code := model.UpdateArticle(id, &data)

	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

func SearchArticle(ctx *gin.Context) {
	title := ctx.Query("title")
	data, code := model.SearchArticle(title)
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    data,
		"message": errmsg.GetErrMsg(code),
	})
}

func DeleteArticle(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	code := model.DeleteArticle(id)
	ctx.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
